@echo off
chcp 65001 >nul
echo 🔧 强力修复npm权限问题（管理员模式）...

:: 检查是否以管理员身份运行
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo ❌ 此脚本需要管理员权限！
    echo 请右键点击此文件，选择"以管理员身份运行"
    pause
    exit /b 1
)

echo ✅ 检测到管理员权限，开始修复...

:: 1. 强制删除npm缓存目录
echo 步骤1: 强制删除npm缓存目录...
if exist "D:\Program Files\nodejs\node_cache" (
    echo 删除系统npm缓存目录...
    takeown /f "D:\Program Files\nodejs\node_cache" /r /d y >nul 2>&1
    icacls "D:\Program Files\nodejs\node_cache" /grant %USERNAME%:F /t >nul 2>&1
    rmdir /s /q "D:\Program Files\nodejs\node_cache" >nul 2>&1
    echo 系统缓存目录已删除
)

:: 2. 创建用户目录下的npm配置
echo 步骤2: 创建用户npm配置...
set USER_NPM_CACHE=%USERPROFILE%\.npm-cache
set USER_NPM_GLOBAL=%USERPROFILE%\npm-global
set USER_NPM_CONFIG=%USERPROFILE%\.npmrc

:: 创建目录
if not exist "%USER_NPM_CACHE%" mkdir "%USER_NPM_CACHE%"
if not exist "%USER_NPM_GLOBAL%" mkdir "%USER_NPM_GLOBAL%"

:: 3. 创建.npmrc配置文件
echo 步骤3: 创建npm配置文件...
echo registry=https://registry.npmmirror.com/ > "%USER_NPM_CONFIG%"
echo cache=%USER_NPM_CACHE% >> "%USER_NPM_CONFIG%"
echo prefix=%USER_NPM_GLOBAL% >> "%USER_NPM_CONFIG%"
echo strict-ssl=false >> "%USER_NPM_CONFIG%"
echo fetch-retry-mintimeout=20000 >> "%USER_NPM_CONFIG%"
echo fetch-retry-maxtimeout=120000 >> "%USER_NPM_CONFIG%"
echo fund=false >> "%USER_NPM_CONFIG%"
echo audit=false >> "%USER_NPM_CONFIG%"

:: 4. 设置环境变量
echo 步骤4: 设置环境变量...
setx NPM_CONFIG_CACHE "%USER_NPM_CACHE%"
setx NPM_CONFIG_PREFIX "%USER_NPM_GLOBAL%"
setx NPM_CONFIG_REGISTRY "https://registry.npmmirror.com/"

:: 5. 更新PATH环境变量
echo 步骤5: 更新PATH环境变量...
for /f "tokens=2*" %%a in ('reg query "HKCU\Environment" /v PATH 2^>nul') do set USER_PATH=%%b
if not defined USER_PATH set USER_PATH=%PATH%
setx PATH "%USER_PATH%;%USER_NPM_GLOBAL%"

:: 6. 清理当前目录
echo 步骤6: 清理当前目录...
if exist "node_modules" rmdir /s /q "node_modules"
if exist "package-lock.json" del "package-lock.json"

:: 7. 测试npm配置
echo 步骤7: 测试npm配置...
call npm config list

echo.
echo ✅ 修复完成！
echo.
echo 📋 修复内容：
echo - 删除了系统npm缓存目录
echo - 创建了用户npm配置: %USER_NPM_CONFIG%
echo - 缓存目录: %USER_NPM_CACHE%
echo - 全局目录: %USER_NPM_GLOBAL%
echo - 使用国内镜像源
echo.
echo 🔄 请重新打开命令提示符，然后运行：
echo    npm install
echo.
pause
